#include "qtch/qtch.h"

static qtch::Logger::ptr logger = QTCH_LOG_NAME("test");

class EchoServer : public qtch::TcpServer{
public:
    EchoServer(int type);
    void handleClient(qtch::Socket::ptr client) override;
private:
    int m_type = 0;
};

EchoServer::EchoServer(int type){
    m_type = type;
}

void EchoServer::handleClient(qtch::Socket::ptr client){
    QTCH_LOG_INFO(logger) << "handleClient" << client;
    qtch::ByteArray::ptr ba(new qtch::ByteArray);
    while(true) {
        ba->clear();
        std::vector<iovec> iovs;
        ba->getWriteBuffer(iovs,1024 * 3);
        int rt = client->recv(&iovs[0],iovs.size());
        if(rt == 0){
            QTCH_LOG_INFO(logger) << "client close:" << client;
            break;
        } else if(rt < 0){
            QTCH_LOG_INFO(logger) << "client errno rt=" << rt
                << " errno=" << errno << " strerro=" << strerror(errno);
            break;
        }
        QTCH_LOG_DEBUG(logger) << "rt=" << rt;
        ba->setWritePosition(ba->getWritePosition() + rt);
        if(m_type == 1) {
            std::cout << ba->toString();
        } else {
            std::cout << ba->toHexString();
        }
        std::cout.flush();
    }
}

int type = 1;
void run() {
    QTCH_LOG_INFO(logger) << "server type=" << type;
    EchoServer::ptr es(new EchoServer(type));
    auto addr = qtch::Address::LookupAny("0.0.0.0:8020");
    while(!es->bind(addr)){
        sleep(2);
    }
    es->start();
}

int main(int argc, char** argv){
    // if(argc < 2){
    //     QTCH_LOG_ERROR(logger) << "used as[" << argv[0] << " -t] or [" << argv[0] << " -b]";
    //     return 0;
    // }
    // if(!strcmp(argv[1], "-b")) {
    //     type = 2;
    // }
    qtch::IOManager iom(2);
    iom.schedule(run);
    iom.start();
    return 0;
}